<template>
  <div class="approval-process-container">
    <el-card class="process-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>第一阶段：审核人配置</span>
        </div>
      </template>
      <el-table :data="stage1ConfigData" style="width: 100%">
        <el-table-column prop="index" label="序号" width="80" align="center" />
        <el-table-column prop="nodeName" label="节点名称" align="center" />
        <el-table-column prop="approverAccount" label="审批人账号" align="center" />
        <el-table-column prop="approverName" label="审批人姓名" align="center" />
        <el-table-column prop="telephone" label="手机号码" align="center" />
        <el-table-column prop="mobile" label="座机号码" align="center" />
        <!-- <el-table-column prop="deptName" label="部门名称" align="center" /> -->
        <el-table-column prop="lastModified" label="最后修改时间" align="center" />
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)"
              >编辑审批人</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="process-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>第一阶段：数源单位审核（科信口）</span>
        </div>
      </template>
      <!-- 添加:span-method="objectSpanMethod"实现合并 -->
      <el-table :data="stage1ReviewData" border style="width: 100%" :span-method="objectSpanMethod">
        <el-table-column prop="index" label="序号" width="80" align="center" />
        <el-table-column prop="nodeName" label="节点名称" align="center" />
        <el-table-column prop="approverAccount" label="审批人账号" align="center" />
        <el-table-column prop="approverName" label="审批人姓名" align="center" />
        <el-table-column prop="telephone" label="手机号码" align="center" />
        <el-table-column prop="mobile" label="座机号码" align="center" />
        <el-table-column prop="deptName" label="部门名称" align="center" />
        <el-table-column prop="lastModified" label="最后修改时间" align="center" />
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row, stage1ReviewData)"
              >编辑审批人</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="process-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>第二阶段：审核人配置</span>
        </div>
      </template>
      <el-table :data="stage2ConfigData" style="width: 100%">
        <el-table-column prop="index" label="序号" width="80" align="center" />
        <el-table-column prop="nodeName" label="节点名称" align="center" />
        <el-table-column prop="approverAccount" label="审批人账号" align="center" />
        <el-table-column prop="approverName" label="审批人姓名" align="center" />
        <el-table-column prop="telephone" label="手机号码" align="center" />
        <el-table-column prop="mobile" label="座机号码" align="center" />
        <!-- <el-table-column prop="deptName" label="部门名称" align="center" /> -->
        <el-table-column prop="lastModified" label="最后修改时间" align="center" />
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)"
              >编辑审批人</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="process-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>第二阶段：业务部门审核（多处室）</span>
          <el-button type="primary" size="small" style="margin-left: 20px" @click="handleAdd">
            新增审批人
          </el-button>
        </div>
      </template>
      <!-- 添加:span-method="objectSpanMethod"实现合并 -->
      <el-table :data="deptAuditData" border style="width: 100%" :span-method="objectSpanMethod">
        <el-table-column prop="index" label="序号" width="80" align="center" />
        <el-table-column prop="nodeName" label="节点名称" align="center" />
        <el-table-column prop="deptName" label="业务部门名称" align="center" />
        <el-table-column prop="approverName" label="审批人姓名" align="center" />
        <el-table-column prop="telephone" label="手机号码" align="center" />
        <el-table-column prop="mobile" label="座机号码" align="center" />
        <el-table-column prop="approverAccount" label="审批人账户" align="center" />
        <el-table-column prop="lastModified" label="最后修改时间" align="center" />
        <el-table-column label="操作" width="240" align="center">
          <template #default="scope">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleEdit(scope.row, deptAuditData)"
              >编辑审批人</el-button
            >
            <el-button
              type="danger"
              link
              size="small"
              style="margin-left: 10px"
              @click="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="`编辑${currentRow?.nodeName}审批人`" width="500px">
      <el-form :model="editForm" :rules="formRules">
        <el-form-item label="部门" prop="deptId">
          <el-select
            v-model="editForm.orgCode"
            filterable
            placeholder="请选择部门"
            style="width: 100%"
            @change="handleDeptChange"
          >
            <el-option
              v-for="dept in deptList"
              :key="dept.orgCode"
              :label="dept.name"
              :value="dept.orgCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审批人" prop="approverName">
          <el-select
            v-model="editForm.approverName"
            placeholder="请选择审批人"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="user in filteredUserList"
              :key="user.id"
              :label="user.nickName"
              :value="user.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="座机号码" prop="telephone">
          <el-input v-model="editForm.mobile" placeholder="请输入座机号码" style="width: 100%" />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="editForm.telephone" placeholder="请输入手机号码" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-model="addDialogVisible"
      :title="isEditingDeptAudit ? '编辑业务部门审核人' : '新增业务部门审核人'"
      width="500px"
    >
      <el-form :model="addForm" :rules="addFormRules">
        <el-form-item label="部门" prop="orgCode">
          <el-select
            v-model="addForm.orgCode"
            filterable
            placeholder="请选择部门"
            style="width: 100%"
            @change="handleAddDeptChange"
          >
            <el-option
              v-for="dept in deptList"
              :key="dept.orgCode"
              :label="dept.name"
              :value="dept.orgCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审批人" prop="approverName">
          <el-select
            v-model="addForm.approverName"
            placeholder="请选择审批人"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="user in addFilteredUserList"
              :key="user.id"
              :label="user.nickName"
              :value="user.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="座机号码" prop="telephone">
          <el-input v-model="addForm.mobile" placeholder="请输入座机号码" style="width: 100%" />
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addForm.telephone" placeholder="请输入手机号码" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import {
  getApprovalList,
  getAllUserList,
  updateApprovalNodeConfig,
  getAllDeptList
} from '@/api/business/approval'
import { ElMessage } from 'element-plus'

// 表格合并相关逻辑
interface SpanMethodProps {
  row: any
  column: any
  rowIndex: number
  columnIndex: number
}

let rowSpansMap = new Map() // 存储需要合并的行信息

// 计算合并行数
const calculateRowSpans = (data: any[]) => {
  rowSpansMap = new Map()
  if (!data.length) return

  let currentNodeName = data[0].nodeName
  let startRow = 0
  let spanCount = 1

  for (let i = 1; i < data.length; i++) {
    if (data[i].nodeName === currentNodeName) {
      spanCount++
    } else {
      rowSpansMap.set(startRow, spanCount)
      currentNodeName = data[i].nodeName
      startRow = i
      spanCount = 1
    }
  }
  // 设置最后一组的合并信息
  rowSpansMap.set(startRow, spanCount)
}

// 合并方法
const objectSpanMethod = ({ row, column, rowIndex, columnIndex }: SpanMethodProps) => {
  // 定义需要合并的列索引（1、2、6列对应的索引为0、1、5）
  const mergeColumns = [0, 1, 7]

  // 检查当前列是否需要合并
  if (mergeColumns.includes(columnIndex)) {
    const span = rowSpansMap.get(rowIndex)
    if (span) {
      return {
        rowspan: span,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
  // 其他列不合并
  return {
    rowspan: 1,
    colspan: 1
  }
}

const stage1ConfigData = ref([])
const stage1ReviewData = ref([])
const stage2ConfigData = ref([])
const userList = ref([])
const dialogVisible = ref(false)
const currentRow = ref<any>(null)
const isStage1ReviewData = ref(false)
const isDeptAuditData = ref(false)
const deptAuditData = ref([])
const isEditingDeptAudit = ref(false)

const editForm = ref({
  approverName: '',
  approverId: '',
  selectedUsers: [],
  originalAuditor: null,
  orgCode: '', // 部门ID仅用于筛选
  deptId: '', // 部门ID仅用于筛选
  telephone: '', // 座机号码
  mobile: '' // 手机号码
})

// 添加表单验证规则
const formRules = ref({
  orgCode: [], // 部门非必填
  approverName: [
    {
      required: true,
      message: '请选择审批人',
      trigger: 'blur'
    }
  ],
  telephone: [], // 座机号码非必填
  mobile: [] // 手机号码非必填
})

// 新增的响应式变量 - 用于独立的新增弹窗
const addDialogVisible = ref(false)
const addForm = ref({
  approverName: '',
  orgCode: '',
  telephone: '',
  mobile: ''
})

const addFormRules = ref({
  orgCode: [{ required: true, message: '请选择部门', trigger: 'blur' }],
  approverName: [{ required: true, message: '请选择审批人', trigger: 'blur' }],
  telephone: [],
  mobile: []
})

// 新增的计算属性 - 用于新增弹窗的用户筛选
const addFilteredUserList = computed(() => {
  if (!addForm.value.orgCode) {
    return userList.value
  }
  return userList.value.filter((user) => user.orgCode === addForm.value.orgCode)
})

// 新增的方法 - 处理新增弹窗的部门切换
const handleAddDeptChange = () => {
  addForm.value.approverName = ''
  addForm.value.telephone = ''
  addForm.value.mobile = ''
}

const handleAdd = () => {
  // 重置新增表单
  addForm.value = {
    approverName: '',
    orgCode: '',
    telephone: '',
    mobile: ''
  }
  addDialogVisible.value = true
}

// 新增的方法 - 提交新增数据
// ... existing code ...
const submitAdd = async () => {
  try {
    // 查找DEPT_AUDIT类型节点（id:7）
    const deptAuditItem = await getApprovalList().then((res) =>
      res?.list?.find((item) => item.id === 7 && item.nodeCode === 'DEPT_AUDIT')
    )

    if (!deptAuditItem) {
      ElMessage.error('未找到业务部门审核配置')
      return
    }

    // 构建审批人数据
    const selectedUser = userList.value.find((user) => user.name === addForm.value.approverName)
    if (!selectedUser) {
      ElMessage.error('未找到所选审批人信息')
      return
    }

    const orgCode = addForm.value.orgCode
    const approverName = addForm.value.approverName
    const mobile = addForm.value.mobile
    const telephone = addForm.value.telephone

    // 获取当前的auditor字符串
    let auditorStr = deptAuditItem.auditor || '{}'

    // 解析包含重复键的JSON字符串为数组对象
    const parseDuplicateKeysJSONToArray = (jsonStr) => {
      const keyValuePairs = []
      const regex = /"([^"]+)":\s*({[^}]*}|"[^"]*"|\d+|true|false|null)/g
      let match

      while ((match = regex.exec(jsonStr)) !== null) {
        const key = match[1]
        let value

        try {
          value = JSON.parse(match[2])
        } catch {
          value = match[2]
        }

        // 将键值对转换为包含索引、deptCode和auditorInfo的对象
        keyValuePairs.push({
          index: keyValuePairs.length,
          deptCode: key,
          auditorInfo: value
        })
      }

      return keyValuePairs
    }

    // 解析auditor字符串为数组对象
    const auditorArray = parseDuplicateKeysJSONToArray(auditorStr)

    // 检查是否存在相同的部门和审批人组合
    const isDuplicate = auditorArray.some((item, index) => {
      // 编辑模式下，排除当前正在编辑的项
      if (isEditingDeptAudit.value) {
        const currentIndex = getCurrentEditingIndex()
        if (index === currentIndex) {
          return false
        }
      }
      return item.deptCode === orgCode && item.auditorInfo.auditor === approverName
    })

    if (isDuplicate) {
      ElMessage.error('已存在相同的部门和审批人组合，请选择不同的组合')
      return
    }

    if (isEditingDeptAudit.value) {
      // 编辑模式：按照索引编辑对应的值

      // 获取当前正在编辑的项的索引
      const targetIndex = getCurrentEditingIndex()

      // 如果找到匹配项，则更新
      if (targetIndex !== -1 && targetIndex < auditorArray.length) {
        // 更新数组中的目标项
        auditorArray[targetIndex] = {
          index: targetIndex,
          deptCode: orgCode,
          auditorInfo: {
            auditor: approverName,
            mobile: mobile,
            telephone: telephone
          }
        }

        // 重新构建auditor字符串
        let newAuditorStr = '{'
        for (let i = 0; i < auditorArray.length; i++) {
          const item = auditorArray[i]
          newAuditorStr += `"${item.deptCode}":${JSON.stringify(item.auditorInfo)}`
          if (i < auditorArray.length - 1) {
            newAuditorStr += ','
          }
        }
        newAuditorStr += '}'
        auditorStr = newAuditorStr
      } else {
        ElMessage.warning('未找到要编辑的审批人数据')
        return
      }
    } else {
      // 新增模式：保持原有逻辑
      // 创建新的审批人数据字符串
      const newAuditorDataStr = `{"${orgCode}":{"auditor":"${approverName}","mobile":"${mobile}","telephone":"${telephone}"}}`

      // 如果原始字符串不是'{}'，则进行合并处理
      if (auditorStr !== '{}') {
        // 移除原始字符串的最后一个'}'，添加逗号和新的数据
        auditorStr = auditorStr.slice(0, -1) + ',' + newAuditorDataStr.slice(1)
      } else {
        auditorStr = newAuditorDataStr
      }
    }

    // 调用updateApprovalNodeConfig接口
    const submitData = {
      auditor: auditorStr,
      id: deptAuditItem.id
    }

    await updateApprovalNodeConfig(submitData)
    ElMessage.success(isEditingDeptAudit.value ? '编辑成功' : '新增成功')
    addDialogVisible.value = false
    isEditingDeptAudit.value = false // 重置编辑状态
    fetchApprovalList()
  } catch (error) {
    console.error(isEditingDeptAudit.value ? '编辑审批人失败:' : '新增审批人失败:', error)
    ElMessage.error(isEditingDeptAudit.value ? '编辑失败' : '新增失败')
  }
}

// 辅助函数：获取当前正在编辑的项的索引
const getCurrentEditingIndex = () => {
  if (!currentRow.value || !currentRow.value.id) {
    return -1
  }

  // 从currentRow.id中提取索引信息
  if (currentRow.value.id.includes('_')) {
    const parts = currentRow.value.id.split('_')
    if (parts.length >= 3) {
      return parseInt(parts[2])
    }
  }

  return -1
}
// ... existing code ...

// 根据部门筛选用户列表的计算属性
const filteredUserList = computed(() => {
  if (!editForm.value.orgCode) {
    return userList.value
  }
  // 根据orgCode筛选用户
  return userList.value.filter((user) => user.orgCode === editForm.value.orgCode)
})

const handleDeptChange = () => {
  // 只有在用户切换部门时才清空表单
  editForm.value.approverName = ''
  editForm.value.telephone = ''
  editForm.value.mobile = ''
}

const handleDelete = async (row) => {
  try {
    // 确认删除
    const confirmResult = await ElMessageBox.confirm('确定要删除该审批人吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    if (confirmResult !== 'confirm') {
      return
    }

    // 查找DEPT_AUDIT类型节点（id:7）
    const deptAuditItem = await getApprovalList().then((res) =>
      res?.list?.find((item) => item.id === 7 && item.nodeCode === 'DEPT_AUDIT')
    )

    if (!deptAuditItem) {
      ElMessage.error('未找到业务部门审核配置')
      return
    }

    // 获取当前的auditor字符串
    let auditorStr = deptAuditItem.auditor || '{}'

    // 解析包含重复键的JSON字符串为数组对象
    const parseDuplicateKeysJSONToArray = (jsonStr) => {
      const keyValuePairs = []
      const regex = /"([^\"]+)":\s*({[^}]*}|"[^"]*"|\d+|true|false|null)/g
      let match

      while ((match = regex.exec(jsonStr)) !== null) {
        const key = match[1]
        let value

        try {
          value = JSON.parse(match[2])
        } catch {
          value = match[2]
        }

        // 将键值对转换为包含索引、deptCode和auditorInfo的对象
        keyValuePairs.push({
          index: keyValuePairs.length,
          deptCode: key,
          auditorInfo: value
        })
      }

      return keyValuePairs
    }

    // 解析auditor字符串为数组对象
    const auditorArray = parseDuplicateKeysJSONToArray(auditorStr)

    // 从row.id中提取索引信息（假设id格式为 '7_部门代码_索引'）
    let targetIndex = -1
    if (row.id && row.id.includes('_')) {
      const parts = row.id.split('_')
      if (parts.length >= 3) {
        targetIndex = parseInt(parts[2])
      }
    }

    // 如果没有从id中提取到索引，则根据部门代码和审批人账号查找
    if (targetIndex === -1 || isNaN(targetIndex) || targetIndex >= auditorArray.length) {
      const targetAuditor = row.approverAccount || row.auditor
      const targetDeptCode = row.deptCode || row.orgCode

      // 查找匹配项的索引
      for (let i = 0; i < auditorArray.length; i++) {
        const item = auditorArray[i]
        if (item.deptCode === targetDeptCode && item.auditorInfo.auditor === targetAuditor) {
          targetIndex = i
          break
        }
      }
    }

    // 如果找到匹配项，则删除
    if (targetIndex !== -1 && targetIndex < auditorArray.length) {
      // 从数组中删除目标项
      auditorArray.splice(targetIndex, 1)

      // 重新构建auditor字符串
      if (auditorArray.length === 0) {
        auditorStr = '{}'
      } else {
        // 构建新的JSON字符串
        let newAuditorStr = '{'
        for (let i = 0; i < auditorArray.length; i++) {
          const item = auditorArray[i]
          newAuditorStr += `"${item.deptCode}":${JSON.stringify(item.auditorInfo)}`
          if (i < auditorArray.length - 1) {
            newAuditorStr += ','
          }
        }
        newAuditorStr += '}'
        auditorStr = newAuditorStr
      }
    } else {
      ElMessage.warning('未找到要删除的审批人数据')
      return
    }

    // 调用updateApprovalNodeConfig接口
    const submitData = {
      auditor: auditorStr,
      id: deptAuditItem.id
    }

    await updateApprovalNodeConfig(submitData)
    ElMessage.success('删除成功')
    fetchApprovalList() // 刷新列表
  } catch (error) {
    // 如果是用户取消，不显示错误信息
    if (error !== 'cancel') {
      console.error('删除审批人失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleEdit = (row: any, data?: any[]) => {
  currentRow.value = row
  // 设置标志位，判断是哪种类型的数据
  isStage1ReviewData.value = data === stage1ReviewData.value
  isDeptAuditData.value = data === deptAuditData.value

  // 关键点：当编辑的是业务部门审核数据时，使用新增弹窗
  if (isDeptAuditData.value) {
    isEditingDeptAudit.value = true
    // 使用addForm填充数据
    addForm.value = {
      approverName: row.approverAccount || '',
      orgCode: '',
      telephone: row.telephone || '',
      mobile: row.mobile || ''
    }

    // 设置部门orgCode
    const userInfo = getUserByApproverName(addForm.value.approverName)
    if (userInfo && userInfo.orgCode) {
      addForm.value.orgCode = userInfo.orgCode
    } else if (row.id && row.id.includes('_')) {
      // 从id中提取orgCode
      addForm.value.orgCode = row.id.split('_')[1]
    }

    addDialogVisible.value = true
  } else {
    // 其他类型数据继续使用原有的编辑逻辑
    editForm.value.approverName = row.approverAccount || ''
    // 保存原始auditor对象
    if (currentRow.value.originalAuditor) {
      editForm.value.originalAuditor = currentRow.value.originalAuditor
    }

    // 设置联系方式
    editForm.value.telephone = row.telephone || ''
    editForm.value.mobile = row.mobile || ''

    // 设置部门（仅用于筛选）
    const userInfo = getUserByApproverName(editForm.value.approverName)
    if (userInfo && userInfo.orgCode) {
      // 使用用户的orgCode
      editForm.value.orgCode = userInfo.orgCode
    } else {
      editForm.value.orgCode = ''
    }

    editForm.value.approverId = row.id
    dialogVisible.value = true
  }
}

// ... existing code ...
const submitEdit = async () => {
  try {
    let auditor = ''

    if (currentRow.value.nodeCode === 'RIGHT' && !isStage1ReviewData.value) {
      // 只有非stage1ReviewData的RIGHT类型才使用多选提交逻辑
      // 检查是否有原始auditor对象，如果有则基于它进行修改
      if (editForm.value.originalAuditor) {
        const originalAuditorObj = JSON.parse(editForm.value.originalAuditor)
        originalAuditorObj['JCB'] = editForm.value.selectedUsers.join(',')
        auditor = JSON.stringify(originalAuditorObj)
      } else {
        auditor = JSON.stringify({
          JCB: editForm.value.selectedUsers.join(',')
        })
      }
    } else {
      // 对于stage1ReviewData、deptAuditData和其他类型，使用单选提交逻辑
      const selectedUser = userList.value.find((user) => user.name === editForm.value.approverName)

      if (selectedUser) {
        // 构建包含审批人、手机号和座机的JSON对象（按指定格式）
        const auditorData = {
          auditor: selectedUser.name,
          mobile: editForm.value.mobile,
          telephone: editForm.value.telephone
        }

        // 处理特殊情况：从id中提取deptId/orgCode
        if (
          (isStage1ReviewData.value || isDeptAuditData.value) &&
          currentRow.value.id.includes('_')
        ) {
          // 关键点：对于DEPT_AUDIT类型，优先使用editForm中的orgCode
          let deptId = currentRow.value.id.split('_')[1]

          // 对于DEPT_AUDIT类型节点，使用editForm.orgCode作为键
          if (isDeptAuditData.value && editForm.value.orgCode) {
            deptId = editForm.value.orgCode
          }

          // 保留原始auditor对象中的其他部门信息
          let auditorObj = {}
          if (editForm.value.originalAuditor) {
            auditorObj = JSON.parse(editForm.value.originalAuditor)
          }

          // 只更新当前编辑的部门信息
          auditorObj[deptId] = auditorData
          auditor = JSON.stringify(auditorObj, null, 8)
        } else {
          // 序列化为带换行和缩进的JSON字符串
          auditor = JSON.stringify(auditorData, null, 8)
        }
      } else {
        auditor = JSON.stringify({})
      }
    }

    // 构建最终提交的对象
    const submitData = {
      auditor: auditor,
      id:
        isStage1ReviewData.value || isDeptAuditData.value
          ? currentRow.value.originalId
          : editForm.value.approverId
    }

    await updateApprovalNodeConfig(submitData)

    ElMessage.success('更新成功')
    dialogVisible.value = false
    fetchApprovalList()
  } catch (error) {
    ElMessage.error('更新失败')
  }
}
// ... existing code ...

// 1. 添加辅助函数，根据审批人name获取对应的用户信息
const getUserByApproverName = (approverName: string) => {
  return userList.value.find((user) => user.name === approverName) || null
}

// 2. 添加辅助函数，根据deptId获取部门名称
const getDeptNameByDeptId = (deptId: string) => {
  if (!deptId) return ''
  const dept = deptList.value.find((dept) => dept.deptId === deptId)
  return dept ? dept.name : ''
}

const parseAuditorInfo = (auditorStr: string) => {
  try {
    if (!auditorStr || auditorStr === '') {
      return { account: '', telephone: '', mobile: '' }
    }

    const auditorObj = JSON.parse(auditorStr)

    // 处理不同格式的auditor对象
    let account = ''
    let telephone = ''
    let mobile = ''

    // 如果auditorObj本身包含auditor、telephone和mobile字段
    if (auditorObj.auditor) {
      account = auditorObj.auditor || ''
      telephone = auditorObj.telephone || ''
      mobile = auditorObj.mobile || ''
    } else {
      // 否则，遍历对象找到第一个非空值作为account
      for (const prop in auditorObj) {
        if (auditorObj[prop] && auditorObj[prop] !== '') {
          // 如果值是对象，可能包含账号和联系方式
          if (typeof auditorObj[prop] === 'object' && auditorObj[prop] !== null) {
            account = auditorObj[prop].auditor || ''
            telephone = auditorObj[prop].telephone || ''
            mobile = auditorObj[prop].mobile || ''
          } else {
            account = auditorObj[prop]
          }
          break
        }
      }
    }

    return { account, telephone, mobile }
  } catch (error) {
    console.error('解析auditor信息失败:', error)
    return { account: auditorStr, telephone: '', mobile: '' }
  }
}

const fetchApprovalList = () => {
  getApprovalList().then((res) => {
    if (res && res.list) {
      // 首先过滤掉id为7的数据项
      const filteredList = res.list.filter((item) => item.id !== 7)

      const deptAuditItem = res.list.find((item) => item.id === 7 && item.nodeCode === 'DEPT_AUDIT')

      // 创建一个统一处理用户显示名称的函数
      const formatApproverName = (userInfo) => {
        if (!userInfo || !userInfo.nickName) return ''
        let displayName = userInfo.nickName
        // 如果有orgName或deptName，添加到nickName后面
        if (
          (userInfo.orgName && userInfo.orgName.trim() !== '') ||
          (userInfo.deptName && userInfo.deptName.trim() !== '')
        ) {
          const deptName = userInfo.orgName || userInfo.deptName
          displayName += `(${deptName})`
        }
        return displayName
      }

      stage1ConfigData.value = filteredList
        .filter((item) => ['LEFT_1', 'LEFT_2', 'LEFT_3'].includes(item.nodeCode))
        .map((item, index) => {
          const { account, telephone, mobile } = parseAuditorInfo(item.auditor)
          const userInfo = getUserByApproverName(account)
          return {
            index: index + 1,
            id: item.id,
            nodeName: item.nodeName,
            nodeCode: item.nodeCode,
            approverAccount: account, // 使用解析出的账号
            approverName: formatApproverName(userInfo) || account, // 使用统一的显示格式
            deptName: getDeptNameByDeptId(userInfo?.deptId || ''), // 添加部门名称
            telephone: telephone || '-', // 座机号码
            mobile: mobile || '-', // 手机号码
            lastModified: formatTime(item.modifyTime),
            originalAuditor: item.auditor // 保存原始auditor对象
          }
        })

      // 处理数源单位审核（RIGHT类型）
      const rightItems = filteredList.filter((item) => item.nodeCode === 'RIGHT')
      stage1ReviewData.value = rightItems.flatMap((item, index) => {
        try {
          // 解析RIGHT类型的auditor字段，它是嵌套的JSON字符串
          const auditorObj = JSON.parse(item.auditor)
          // 转换为数组格式
          return Object.entries(auditorObj).map(([deptId, auditorInfo], i) => {
            // 提取审批人账号、座机和手机号
            let account = ''
            let telephone = ''
            let mobile = ''

            // 检查auditorInfo是否为对象
            if (typeof auditorInfo === 'object' && auditorInfo !== null) {
              account = auditorInfo.auditor || ''
              telephone = auditorInfo.telephone || ''
              mobile = auditorInfo.mobile || ''
            } else {
              account = auditorInfo || ''
            }

            // 获取用户信息
            const userInfo = account ? getUserByApproverName(account) : null

            // 获取部门名称，如果获取不到则直接显示部门ID
            let deptName = deptId
            if (deptId) {
              const deptInfo = getDeptNameByDeptId(deptId)
              if (deptInfo && deptInfo.trim() !== '') {
                deptName = deptInfo
              }
            }

            // 格式化索引，确保每条记录都有唯一索引
            const recordIndex = index * 100 + i + 1

            return {
              index: recordIndex,
              id: `${item.id}_${deptId}`, // 确保每条记录ID唯一
              nodeName: item.nodeName || '-',
              nodeCode: item.nodeCode || '-',
              approverAccount: account || '-', // 审批人账号
              approverName: formatApproverName(userInfo) || account || '-', // 使用统一的显示格式
              deptName: deptName || '-', // 部门名称
              telephone: telephone || '-', // 座机号码
              mobile: mobile || '-', // 手机号码
              lastModified: formatTime(item.modifyTime) || '-',
              originalId: item.id,
              originalAuditor: item.auditor // 保存原始auditor对象
            }
          })
        } catch (error) {
          console.error('解析RIGHT类型auditor失败:', error)
          return []
        }
      })

      // 处理科信处多人审核（DEPT_AUDIT类型）
      if (deptAuditItem) {
        try {
          // 自定义解析包含重复键的JSON字符串
          const parseDuplicateKeysJSON = (jsonStr) => {
            // 使用正则表达式匹配键值对
            const keyValuePairs = []
            const regex = /"([^"]+)":\s*({[^}]*}|"[^"]*"|\d+|true|false|null)/g
            let match

            while ((match = regex.exec(jsonStr)) !== null) {
              const key = match[1]
              let value

              try {
                value = JSON.parse(match[2])
              } catch {
                value = match[2]
              }

              keyValuePairs.push([key, value])
            }

            return keyValuePairs
          }

          // 解析DEPT_AUDIT类型的auditor字段，它是嵌套的JSON字符串
          const auditorPairs = parseDuplicateKeysJSON(deptAuditItem.auditor)

          // 转换为数组格式
          deptAuditData.value = auditorPairs.map(([deptId, auditorInfo], i) => {
            // 提取审批人账号、座机和手机号
            let account = ''
            let telephone = ''
            let mobile = ''

            // 检查auditorInfo是否为对象
            if (typeof auditorInfo === 'object' && auditorInfo !== null) {
              account = auditorInfo.auditor || ''
              telephone = auditorInfo.telephone || ''
              mobile = auditorInfo.mobile || ''
            } else {
              account = auditorInfo || ''
            }

            // 获取用户信息
            const userInfo = account ? getUserByApproverName(account) : null

            // 获取部门名称，如果获取不到则直接显示部门ID
            let deptName = deptId
            if (deptId) {
              const deptInfo = getDeptNameByDeptId(deptId)
              if (deptInfo && deptInfo.trim() !== '') {
                deptName = deptInfo
              }
            }

            return {
              index: i + 1,
              id: `${deptAuditItem.id}_${deptId}_${i}`, // 确保每条记录ID唯一
              nodeName: deptAuditItem.nodeName || '-',
              nodeCode: deptAuditItem.nodeCode || '-',
              approverAccount: account || '-', // 审批人账号
              approverName: formatApproverName(userInfo) || account || '-', // 使用统一的显示格式
              deptName: deptName || '-', // 业务部门名称
              telephone: telephone || '-', // 添加座机号码字段
              mobile: mobile || '-', // 添加手机号码字段
              lastModified: formatTime(deptAuditItem.modifyTime) || '-',
              originalId: deptAuditItem.id,
              originalAuditor: deptAuditItem.auditor // 保存原始auditor对象
            }
          })

          // 计算合并行数
          calculateRowSpans(deptAuditData.value)
        } catch (error) {
          console.error('解析DEPT_AUDIT类型auditor失败:', error)
          deptAuditData.value = []
        }
      }

      // 计算合并行数
      calculateRowSpans(stage1ReviewData.value)

      // 处理第二阶段配置
      stage2ConfigData.value = filteredList
        .filter((item) =>
          ['DEPT_SELECT', 'LEADER_AUDIT', 'NOTIFY', 'DEPT_AUDIT'].includes(item.nodeCode)
        )
        .map((item, index) => {
          const { account, telephone, mobile } = parseAuditorInfo(item.auditor)
          const userInfo = getUserByApproverName(account)
          return {
            index: index + 1,
            id: item.id,
            nodeName: item.nodeName,
            nodeCode: item.nodeCode,
            approverAccount: account, // 使用解析出的账号
            approverName: formatApproverName(userInfo) || account, // 使用统一的显示格式
            deptName: getDeptNameByDeptId(userInfo?.deptId || ''), // 添加部门名称
            telephone: telephone || '-', // 座机号码
            mobile: mobile || '-', // 手机号码
            lastModified: formatTime(item.modifyTime),
            originalAuditor: item.auditor // 保存原始auditor对象
          }
        })
    }
  })
}

const formatTime = (timestamp: any) => {
  // 检查timestamp是否为字符串格式的日期时间
  if (typeof timestamp === 'string') {
    return timestamp
  }

  const date = new Date(timestamp)
  return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`
}

const padZero = (num: number) => {
  return num < 10 ? `0${num}` : num
}

const deptList = ref([])
onMounted(async () => {
  try {
    // 并行获取部门列表和用户列表数据
    const [deptRes, userRes] = await Promise.all([getAllDeptList(), getAllUserList()])

    // 确保两个数据源都成功获取后再设置数据
    deptList.value = deptRes || []
    userList.value = userRes || []

    // 等部门和用户数据都准备好后，再获取审批列表
    fetchApprovalList()
  } catch (error) {
    console.error('获取部门或用户数据失败:', error)
    // 即使出错也尝试获取审批列表，确保基础功能可用
    fetchApprovalList()
  }
})
</script>

<style scoped lang="scss">
.approval-process-container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.process-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.el-table {
  margin-top: 10px;
}

.el-button {
  padding: 5px 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
